package com.taptech.doufu.services.personalcenter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Base64;
import android.widget.Toast;

import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WbAuthListener;
import com.taptech.doufu.ui.activity.PersonalInviteWeiboContactActivity;
import com.taptech.doufu.app.WeMediaApplication;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.listener.HttpResponseListener;
import com.taptech.doufu.listener.ILoginCallback;
import com.taptech.doufu.services.BaseService;
import com.taptech.doufu.util.DiaobaoUtil;
import com.taptech.doufu.util.TTLog;
import com.taptech.doufu.util.UIUtil;
import com.taptech.doufu.net.httputils.HttpRequestObject;
import com.taptech.doufu.net.httputils.HttpUtil;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.LinkedList;
import java.util.List;


public class WeiboService extends BaseService {
    public static final String SINA_WEIBO_FRIENDS_URL = "https://api.weibo.com/2/friendships/followers.json";
    public static final String SINA_WEIBO_USER_INFO_URL = "https://api.weibo.com/2/users/show.json";

    private static final String SEND_WEIBO_MESSAGE_URL = "https://upload.api.weibo.com/2/statuses/upload.json";

    private static final String DEFAULT_URL = "http://" + Constant.HOST_NAME + "/index.php/member/social_bind_register";

    private static final String REFRESH_URL = "https://api.weibo.com/oauth2/access_token";


    public static final int HANDLE_WEIBO_BIND_OR_REGIST = 1231;


    /**
     * 封装了 "access_token"，"expires_in"，"refresh_token"，并提供了他们的管理功能
     */
    public static Oauth2AccessToken mAccessToken;

    /**
     * 注意：SsoHandler 仅当 SDK 支持 SSO 时有效
     */
//    public SsoHandler mSsoHandler;

    private static WeiboService instance = new WeiboService();

    public static final String SCOPE = "email,direct_messages_read,direct_messages_write," + "friendships_groups_read,friendships_groups_write,statuses_to_me_read," + "follow_app_official_microblog," + "invitation_write";

    private Activity activity;

    private boolean isLogin;

    private WeiboService() { }

    public static WeiboService getInstance() {
        if (mAccessToken == null) {
            mAccessToken = AccessTokenKeeper.readAccessToken(WeMediaApplication.applicationContext);
        }
        return instance;
    }



    public void ssoAuthorize(Activity activity, final ILoginCallback iLoginCallback) {
        this.activity = activity;
//        mSsoHandler = new SsoHandler(activity);
//
//        if (isLogin == true) {
//            UIUtil.toastMessage(activity, "别点了，微博正在启动...");
//            return;
//        }
//        isLogin = true;
//
//        try {
//            mSsoHandler.authorize(new WbAuthListener() {
//                @Override
//                public void onSuccess(Oauth2AccessToken oauth2AccessToken) {
//                    mAccessToken = oauth2AccessToken;
//                    isLogin = false;
//                    if (mAccessToken.isSessionValid()) {
//                        // 保存 Token 到 SharedPreferences
//                        AccessTokenKeeper.writeAccessToken(WeMediaApplication.applicationContext, mAccessToken);
//                        iLoginCallback.token(mAccessToken.getToken(),mAccessToken.getUid(),"微博授权成功，正在获取用户信息");
//                    } else {
//                        iLoginCallback.token("","","授权失败，请重新登录");
//                    }
//                }
//
//                @Override
//                public void cancel() {
//                    isLogin = false;
//                    iLoginCallback.token("","","授权失败，请重新登录");
//                    UIUtil.dismissDialog();
//                }
//
//                @Override
//                public void onFailure(WbConnectErrorMessage wbConnectErrorMessage) {
//                    isLogin = false;
//                    iLoginCallback.token("","","授权失败，请重新登录");
//                    UIUtil.dismissDialog();
//                }
//            });
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }



    public void ssoAuthorize(final Activity activity, final boolean isFlag, final boolean isInvite) {
        this.activity = activity;
//        mSsoHandler = new SsoHandler(activity);
//        if (isLogin == true) {
//            UIUtil.toastMessage(activity, "别点了，微博正在启动...");
//            return;
//        }
//        isLogin = true;
//        try {
//            mSsoHandler.authorize(new WbAuthListener() {
//                @Override
//                public void onSuccess(Oauth2AccessToken oauth2AccessToken) {
//                    mAccessToken = oauth2AccessToken;
//                    isLogin = false;
//                    if (isInvite) {
//                        Intent intent = new Intent(activity, PersonalInviteWeiboContactActivity.class);
//                        intent.putExtra(Constant.GROUP_ID, 0);
//                        activity.startActivity(intent);
//                    }
//                }
//
//                @Override
//                public void cancel() {
//                    isLogin = false;
//
//                    TTLog.i("TAG", "onCancel()");
//                }
//
//                @Override
//                public void onFailure(WbConnectErrorMessage wbConnectErrorMessage) {
//                    isLogin = false;
//
//                    UIUtil.toastMessage(WeiboService.this.activity, "微博授权失败:" + wbConnectErrorMessage.getErrorMessage());
//                }
//            });
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    public void bindWebiAccount(Activity activity) {
        this.activity = activity;
//        mSsoHandler = new SsoHandler(activity);
//        try {
//            mSsoHandler.authorize(new WbAuthListener() {
//                @Override
//                public void onSuccess(Oauth2AccessToken oauth2AccessToken) {
//                    mAccessToken = oauth2AccessToken;
//                    if (mAccessToken.isSessionValid())
//                    {
//                        // 保存 Token 到 SharedPreferences
//                        AccessTokenKeeper.writeAccessToken(WeMediaApplication.applicationContext, mAccessToken);
//                        WeiboService.this.activity.runOnUiThread(new Runnable()
//                        {
//
//                            @Override
//                            public void run()
//                            {
//                                UIUtil.toastMessage(WeiboService.this.activity, "微博授权成功，正在获取用户信息");
//                            }
//                        });
//                        loadWeiboUserInfo(oauth2AccessToken);
//
//                    }
//                }
//
//                @Override
//                public void cancel() {
//                    TTLog.i("TAG", "onCancel()");
//                }
//
//                @Override
//                public void onFailure(WbConnectErrorMessage wbConnectErrorMessage) {
//                    UIUtil.toastMessage(WeiboService.this.activity, "微博授权失败:" + wbConnectErrorMessage.getErrorMessage());
//                }
//            });
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    public void sinaAuthorizeCallBack(int requestCode, int resultCode, Intent data){
//        if (mSsoHandler != null){
//            mSsoHandler.authorizeCallBack(requestCode , resultCode , data);
//        }
    }

    public void refreshTokenRequest(Context context) {    // https://api.weibo.com/oauth2/access_token?client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&grant_type=refresh_token&redirect_uri=YOUR_REGISTERED_REDIRECT_URI&refresh_token=…
        final Oauth2AccessToken token = WeiboService.getInstance().mAccessToken;
//        WeiboParameters params = new WeiboParameters(Constant.APP_KEY);
//        params.add("client_id", Constant.APP_KEY);
//        params.add("client_secret", "1977434707b47437b33b24c887f7fafb");
//        params.add("grant_type", "refresh_token");
//        params.add("refresh_token", token.getRefreshToken());
//        try {
//            params.add("redirect_uri", URLEncoder.encode(Constant.REDIRECT_URL , "utf-8"));
//            AsyncWeiboRunner runner = new AsyncWeiboRunner(activity);
//            runner.requestAsync(REFRESH_URL, params, "POST", new RequestListener() {
//                @Override
//                public void onComplete(String arg0) {
//                    try {
//                        JSONObject jsonObject = new JSONObject(arg0);
//                        if (WeiboService.getInstance().mAccessToken != null && jsonObject != null){
//
//                            WeiboService.getInstance().mAccessToken.setUid(jsonObject.getString("uid"));
//                            WeiboService.getInstance().mAccessToken.setExpiresIn(jsonObject.getString("expires_in"));
//                            WeiboService.getInstance().mAccessToken.setRefreshToken(jsonObject.getString("refresh_token"));
//                            WeiboService.getInstance().mAccessToken.setToken(jsonObject.getString("access_token"));
//                            AccessTokenKeeper.writeAccessToken(WeMediaApplication.applicationContext, mAccessToken);
//                        }
//
//
//                    } catch (JSONException e) {
//                        // TODO Auto-generated catch block
//                        e.printStackTrace();
//                    }
//
//                }
//
//                @Override
//                public void onWeiboException(WeiboException e) {
//
//                }
//
//            });
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//

    }



//    private void loadWeiboUserInfo(final Oauth2AccessToken oauth2AccessToken) {
//        WeiboParameters params = new WeiboParameters(Constant.APP_KEY);
//        params.add("source", Constant.APP_KEY);
//        params.add("uid", mAccessToken.getUid());
//        params.add("access_token", mAccessToken.getToken());
//        AsyncWeiboRunner runner = new AsyncWeiboRunner(activity);
//        runner.requestAsync(SINA_WEIBO_USER_INFO_URL, params, "GET", new RequestListener() {
//
//            @Override
//            public void onComplete(String arg0) {
//                try {
//                    activity.runOnUiThread(new Runnable()
//                    {
//                        @Override
//                        public void run()
//                        {
//                            UIUtil.toastMessage(activity, "获取微博用户信息成功，正在登录...");
//                            UIUtil.dismissDialog();
//                        }
//                    });
//                    JSONObject obj = new JSONObject(arg0);
//                    final String nickname = obj.getString("screen_name");
//                    final String id = mAccessToken.getUid();
//                    final String expires_in = String.valueOf(oauth2AccessToken.getExpiresTime());
//                    final String access_token = mAccessToken.getToken();
//
//                    List<NameValuePair> lsit = new LinkedList<NameValuePair>();
//                    NameValuePair tokenValue = new BasicNameValuePair("auth_token", id);
//                    NameValuePair expiresValue = new BasicNameValuePair("expires_in", expires_in);
//                    NameValuePair nickValue = new BasicNameValuePair("nickname", nickname);
//                    NameValuePair avatarValue = new BasicNameValuePair("head_img", DiaobaoUtil.getStringFromJSONObject(obj, "profile_image_url"));
//
//                    NameValuePair typeValue = new BasicNameValuePair("social_type", "1");
//
//                    String uid = "0";
//                    if (AccountService.getInstance().getBaseAccount() != null)
//                    {
//                        uid = AccountService.getInstance().getBaseAccount().getUid();
//                    }
//                    NameValuePair uidValue = new BasicNameValuePair("uid", uid);
//                    NameValuePair accessValue = new BasicNameValuePair("access_token", access_token);
//                    lsit.add(uidValue);
//                    lsit.add(typeValue);
//                    lsit.add(tokenValue);
//                    lsit.add(expiresValue);
//                    lsit.add(avatarValue);
//                    lsit.add(nickValue);
//                    lsit.add(accessValue);
//
//                    HttpRequestObject request = new HttpRequestObject();
//                    request.setHandleType(HANDLE_WEIBO_BIND_OR_REGIST);
//                    request.setUrl(DEFAULT_URL);
//                    request.setData(lsit);
//                    request.setListener((HttpResponseListener) activity);
//                    HttpUtil.sendLockedPostRequest(request, activity);
//
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//
//            @Override
//            public void onWeiboException(WeiboException e) {
//                activity.runOnUiThread(new Runnable()
//                {
//                    @Override
//                    public void run()
//                    {
//                        UIUtil.toastMessage(activity, "获取微博用户信息失败");
//                        UIUtil.dismissDialog();
//                    }
//                });
//            }
//        });
//    }

//    public LinkedList<Object> getSinaWeiboFriendsList(RequestListener listener, int pageIndex) {
//        if (mAccessToken == null || !mAccessToken.isSessionValid()) {
//            Toast.makeText(WeMediaApplication.applicationContext, "请先进行新浪微博授权", Toast.LENGTH_SHORT).show();
//            return null;
//        }
//        LinkedList<Object> list = new LinkedList<Object>();
//        WeiboParameters params = new WeiboParameters(Constant.APP_KEY);
//        params.add("source", Constant.APP_KEY);
//        params.add("uid", mAccessToken.getUid());
//        params.add("access_token", mAccessToken.getToken());
//        params.add("cursor", pageIndex);
//        params.add("count", 50);
//
//        AsyncWeiboRunner runner = new AsyncWeiboRunner(activity);
//        runner.requestAsync(SINA_WEIBO_FRIENDS_URL, params, "GET", listener);
//        return list;
//    }

    private void registWeiboUser(Bundle values) {
        try {
            final String nickname = values.getString("com.sina.weibo.intent.extra.NICK_NAME");
            final byte bts[] = values.getByteArray("com.sina.weibo.intent.extra.USER_ICON");
            final String id = values.getString("uid");
            final String expires_in = values.getString("expires_in");
            final String access_token = values.getString("access_token");
            List<NameValuePair> lsit = new LinkedList<>();
            if (bts != null) {
                NameValuePair avatarValue = new BasicNameValuePair("avatar", Base64.encodeToString(bts, Base64.DEFAULT));
                lsit.add(avatarValue);
            } else {

            }
            NameValuePair tokenValue = new BasicNameValuePair("auth_token", id);
            NameValuePair expiresValue = new BasicNameValuePair("expires_in", expires_in);
            NameValuePair nickValue = new BasicNameValuePair("nickname", nickname);

            NameValuePair typeValue = new BasicNameValuePair("social_type", "1");
            String uid = "0";
            if (AccountService.getInstance().getBaseAccount() != null) {
                uid = AccountService.getInstance().getBaseAccount().getUid();
            }
            NameValuePair uidValue = new BasicNameValuePair("uid", uid);
            NameValuePair accessValue = new BasicNameValuePair("access_token", access_token);
            lsit.add(uidValue);
            lsit.add(typeValue);
            lsit.add(tokenValue);
            lsit.add(expiresValue);
            lsit.add(nickValue);
            lsit.add(accessValue);

            HttpRequestObject request = new HttpRequestObject();
            request.setHandleType(HANDLE_WEIBO_BIND_OR_REGIST);
            request.setUrl(DEFAULT_URL);
            request.setData(lsit);
            request.setListener((HttpResponseListener) activity);
            HttpUtil.sendLockedPostRequest(request, activity);

        } catch (Exception e)
        {
            e.printStackTrace();
        }

    }


//    public void sendWeiboMessage(String nickName, String inviteCode, String groupName, RequestListener listener) {
//        try {
//            if (mAccessToken == null) {
//                Toast.makeText(WeMediaApplication.applicationContext, "请先进行新浪微博授权", Toast.LENGTH_SHORT).show();
//                return;
//            }
//            WeiboParameters params = new WeiboParameters(Constant.APP_KEY);
//            params.add("source", Constant.APP_KEY);
//            params.add("access_token", mAccessToken.getToken());
//            params.add("pic", Constant.AppDir.DIR_CACHE_IMAGE + "diaobao_test.png");
//            params.add("status", URLEncoder.encode(PersonalInfoService.getInstance().getInviteMessage(inviteCode, groupName) + "@" + nickName, "UTF-8"));
//            AsyncWeiboRunner runner = new AsyncWeiboRunner(activity);
//            runner.requestAsync(SEND_WEIBO_MESSAGE_URL, params, "POST", listener);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }


}
